package cn.wjssl.trigger.listener;

import cn.wjssl.domain.award.event.SendAwardMessageEvent;
import cn.wjssl.domain.award.model.entity.DistributeAwardEntity;
import cn.wjssl.domain.award.service.IAwardService;
import cn.wjssl.types.event.BaseEvent;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用户奖品记录消息消费者
 */
@Slf4j
@Component
public class SendAwardCustomer {

    @Value("${spring.rabbitmq.topic.send_award}")
    private String topic;

    @Resource
    private IAwardService awardService;

    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.send_award}"))
    public void listener(String message) {
        try {
            log.info("监听用户奖品发送消息 topic: {} message: {}", topic, message);
            // 1. 转换中奖记录消息
            // 获取消息体 {id, timestamp, data}
            BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage> sendMsg = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendAwardMessageEvent.SendAwardMessage>>() {
            }.getType());
            // 获取消息体data, 就是 SendAwardMessage 类
            SendAwardMessageEvent.SendAwardMessage data = sendMsg.getData();

            // 创建奖品发放实体类
            DistributeAwardEntity distributeAwardEntity = DistributeAwardEntity.builder()
                    .userId(data.getUserId())
                    .awardId(data.getAwardId())
                    .orderId(data.getOrderId())
                    .awardConfig(data.getAwardConfig()).build();

            // 调用方法进行发奖
            awardService.distributeAward(distributeAwardEntity);

        } catch (Exception e) {
            log.error("监听用户奖品发送消息，消费失败 topic: {} message: {}", topic, message);
            throw e;
        }
    }

}
